<template>
  <!-- 使用 img 标签动态更新 src 实现帧动画 -->
  <img :src="currentFrameSrc" :width="frameWidth" :height="frameHeight" />
</template>

<script>
export default {
  name: "SequenceSpriteAnimation",
  props: {
    // 帧图片数组，每个元素为图片 URL
    frames: {
      type: Array,
      required: true
    },
    // 每秒帧数
    fps: {
      type: Number,
      default: 24
    },
    // 是否循环播放
    loop: {
      type: Boolean,
      default: true
    },
    // 每一帧的宽度（px）
    frameWidth: {
      type: Number,
      required: true
    },
    // 每一帧的高度（px）
    frameHeight: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      currentFrame: 0,
      animationFrameId: null,
      lastTime: 0,
      interval: 1000 / this.fps,
      playing: true
    };
  },
  computed: {
    // 当前帧对应的图片 URL
    currentFrameSrc() {
      return this.frames[this.currentFrame];
    }
  },
  methods: {
    // 使用 requestAnimationFrame 实现动画更新
    tick(timestamp) {
      if (!this.lastTime) {
        this.lastTime = timestamp;
      }
      const delta = timestamp - this.lastTime;
      if (delta > this.interval) {
        this.currentFrame++;
        if (this.currentFrame >= this.frames.length) {
          if (this.loop) {
            this.currentFrame = 0;
          } else {
            this.currentFrame = this.frames.length - 1;
            return;
          }
        }
        this.lastTime = timestamp;
      }
      if (this.playing) {
        this.animationFrameId = requestAnimationFrame(this.tick);
      }
    },
    // 播放动画
    play() {
      if (!this.playing) {
        this.playing = true;
        this.lastTime = 0;
        this.animationFrameId = requestAnimationFrame(this.tick);
      }
    },
    // 暂停动画
    pause() {
      this.playing = false;
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
        this.animationFrameId = null;
      }
    },
    // 重置动画
    reset() {
      this.pause();
      this.currentFrame = 0;
    }
  },
  mounted() {
    this.playing = true;
    this.animationFrameId = requestAnimationFrame(this.tick);
  },
  beforeDestroy() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId);
    }
  }
};
</script>

<style scoped>
/* 根据需要添加样式 */
</style>
